 let http = require('http');
 let urlFail= require('url');
 let fs = require('fs');
 let queryStr = require('querystring');

 let users = {};
 http.createServer((request,response)=>{

    let str = '';

    //解析数据
    request.on('data',function(data){
           str +=data;
    })
    request.on('end',function(){
         let obj = urlFail.parse(request.url,true);
        //  console.log(obj,'url')
         let url = obj.pathname;
         let GET = obj.query;
         let POST = queryStr.parse(str);
         console.log(str,'url')
 
        //  console.log(url,'url')
        //  console.log(GET,'GET')

       

         //区分接口或者文件
        if(url=='/user'){ 
            //   console.log(POST,'POST')
            //接口
             if(GET.act === 'reg'){//注册

                //查询用户是否存在注册过
                 if(users[GET.ussName]){
                    response.write('{"ok":false,msg:"此用户已经注册"}')
                 }else{
                       //插入用户
                       users[GET.ussName] = GET.psd
                       response.write('{"ok":true,msg:"恭喜，注册成功了"}')
                 }
               

             }else if(POST.act === 'login'){//登陆
                //查询用户是否存在
                if(!users[POST.ussName]){
                    response.write('{"ok":false,msg:"此用户不存在"}')
                }else{
                       //检测密码是否正确
                       if(POST.psd == users[POST.ussName]){
                            //登陆
                            response.write('{"ok":true,msg:"恭喜，登陆成功了"}')
                       }else{
                        response.write('{"ok":true,msg:"密码错误请重试"}')
                       }
                
                    
                }
                

             }else{
                response.write('{"ok":false,msg:"未知的错误"}')
             }
             response.end();

        }else{
            //  读取文件
            let urlPath = './day1/www' + url;
            console.log(urlPath,"urlPath")
            fs.readFile(urlPath,function(err,data){
                if(err){
                    response.write('404');

                }else{
                    response.write(data);
                }
                response.end();

             })
        }

     

    })

    // /user?act=reg&ussName='xxx'&psd=123456  注册   {ok:false,msg:'dddd'}

    // /user?act=login&ussName='xxx'&psd=123456  登陆 {ok:true,msg:'dddd'}
  
 }).listen(8787)